#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import threading
import subprocess
from datetime import timedelta
from pathlib import Path

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.slider import Slider
from kivy.uix.spinner import Spinner
from kivy.uix.progressbar import ProgressBar
from kivy.uix.popup import Popup
from kivy.uix.filechooser import FileChooserListView
from kivy.uix.scrollview import ScrollView
from kivy.uix.gridlayout import GridLayout
from kivy.clock import Clock
from kivy.metrics import dp
from kivy.core.window import Window
from kivy.core.text import LabelBase
from kivy.resources import resource_add_path
from kivy.utils import platform as kivy_platform

# 导入视频处理工具
from video_utils import VideoInfo, VideoSplitter, format_duration, format_file_size, validate_split_points
from android_utils import AndroidPermissions, AndroidFileManager, AndroidNotifications, get_android_info
from font_config import setup_fonts, get_font_name

try:
    from plyer import filechooser
    PLYER_AVAILABLE = True
except ImportError:
    PLYER_AVAILABLE = False

try:
    from ffpyplayer.player import MediaPlayer
    FFPYPLAYER_AVAILABLE = True
except ImportError:
    FFPYPLAYER_AVAILABLE = False


class SplitPoint:
    """拆分点类"""
    def __init__(self, time_seconds):
        self.time_seconds = time_seconds
        self.time_str = self.seconds_to_time_str(time_seconds)
    
    def update_video_info_display(self):
        """更新视频信息显示"""
        if self.video_info:
            info_text = (f"分辨率: {self.video_info.get_resolution_string()}\n"
                        f"时长: {self.video_info.get_duration_string()}\n"
                        f"格式: {self.video_info.format_name}")
            # 可以在界面上显示这些信息


class VideoSplitterApp(App):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.selected_video_path = None
        self.video_info = None
        self.video_splitter = VideoSplitter()
        self.split_points = []
        self.current_position = 0
        self.media_player = None
        self.is_playing = False
        self.output_dir = None
        
        # Android相关
        self.android_permissions = AndroidPermissions()
        self.android_file_manager = AndroidFileManager()
        self.android_notifications = AndroidNotifications()
        self.permissions_requested = False
        
        # 设置字体
        self.font_name = setup_fonts() or 'Roboto'  # 使用备用字体名
        
    def get_font_name_safe(self):
        """安全获取字体名称"""
        return self.font_name if hasattr(self, 'font_name') and self.font_name else None
    
    def build(self):
        Window.clearcolor = (0.95, 0.95, 0.95, 1)
        
        # 主布局
        main_layout = BoxLayout(orientation='vertical', padding=dp(10), spacing=dp(10))
        
        # 标题
        title = Label(
            text='视频拆分工具',
            size_hint_y=None,
            height=dp(50),
            font_size='20sp',
            font_name=self.get_font_name_safe(),
            color=(0.2, 0.2, 0.2, 1)
        )
        main_layout.add_widget(title)
        
        # 文件选择区域
        file_section = self.create_file_section()
        main_layout.add_widget(file_section)
        
        # 视频控制区域
        self.video_section = self.create_video_section()
        main_layout.add_widget(self.video_section)
        
        # 拆分点管理区域
        split_section = self.create_split_section()
        main_layout.add_widget(split_section)
        
        # 输出设置区域
        output_section = self.create_output_section()
        main_layout.add_widget(output_section)
        
        # 处理区域
        process_section = self.create_process_section()
        main_layout.add_widget(process_section)
        
        # 在UI创建完成后请求Android权限
        Clock.schedule_once(lambda dt: self.request_android_permissions(), 0.5)
        
        return main_layout
    
    def request_android_permissions(self):
        """请求Android权限"""
        if not self.permissions_requested:
            self.permissions_requested = True
            try:
                # 只在Android平台请求权限
                if kivy_platform == 'android':
                    self.android_permissions.request_storage_permissions(
                        callback=self.on_permissions_result
                    )
                else:
                    # 非Android平台直接设置为已授权
                    self.on_permissions_result(True)
            except Exception as e:
                print(f"Permission request failed: {e}")
                # 权限请求失败时，仍然允许应用继续运行
                self.on_permissions_result(False)
    
    def on_permissions_result(self, granted):
        """权限请求结果回调"""
        if granted:
            print("Storage permissions granted")
            # 设置默认输出目录
            if not self.output_dir:
                if kivy_platform == 'android':
                    self.output_dir = self.android_permissions.create_app_directory()
                    if self.output_dir and hasattr(self, 'output_label'):
                        self.output_label.text = f'输出到: VideoSplitter'
                else:
                    # 非Android平台使用当前目录
                    self.output_dir = os.getcwd()
                    if hasattr(self, 'output_label'):
                        self.output_label.text = f'输出到: 当前目录'
        else:
            # 只在Android平台显示权限错误
            if kivy_platform == 'android':
                if hasattr(self, 'show_error'):
                    self.show_error("需要存储权限才能正常使用应用")
                else:
                    print("需要存储权限才能正常使用应用")
    
    def get_android_video_files(self):
        """获取Android设备上的视频文件"""
        try:
            # 尝试从媒体库获取
            videos = self.android_file_manager.scan_media_store()
            if not videos:
                # 备用方案：获取最近的视频文件
                videos = self.android_file_manager.get_recent_videos()
            return videos
        except Exception as e:
            print(f"Error getting Android videos: {e}")
            return []
    
    def create_file_section(self):
        """创建文件选择区域"""
        layout = BoxLayout(orientation='vertical', size_hint_y=None, height=dp(120), spacing=dp(5))
        
        # 文件选择按钮
        select_btn = Button(
            text='选择视频文件',
            size_hint_y=None,
            height=dp(50),
            background_color=(0.3, 0.6, 0.9, 1),
            font_name=self.get_font_name_safe()
        )
        select_btn.bind(on_press=self.select_video_file)
        layout.add_widget(select_btn)
        
        # 选中文件显示
        self.file_label = Label(
            text='未选择文件',
            size_hint_y=None,
            height=dp(60),
            text_size=(None, None),
            halign='center',
            font_name=self.get_font_name_safe(),
            color=(0.4, 0.4, 0.4, 1)
        )
        layout.add_widget(self.file_label)
        
        return layout
    
    def create_video_section(self):
        """创建视频控制区域"""
        layout = BoxLayout(orientation='vertical', size_hint_y=None, height=dp(150), spacing=dp(5))
        
        # 播放控制
        control_layout = BoxLayout(orientation='horizontal', size_hint_y=None, height=dp(50), spacing=dp(10))
        
        self.play_btn = Button(
            text='播放',
            size_hint_x=0.3,
            background_color=(0.2, 0.7, 0.2, 1),
            disabled=True,
            font_name=self.get_font_name_safe()
        )
        self.play_btn.bind(on_press=self.toggle_play)
        control_layout.add_widget(self.play_btn)
        
        self.position_label = Label(
            text='00:00:00 / 00:00:00',
            size_hint_x=0.7,
            font_name=self.get_font_name_safe(),
            color=(0.3, 0.3, 0.3, 1)
        )
        control_layout.add_widget(self.position_label)
        
        layout.add_widget(control_layout)
        
        # 进度条
        self.progress_slider = Slider(
            min=0,
            max=100,
            value=0,
            size_hint_y=None,
            height=dp(40),
            disabled=True
        )
        self.progress_slider.bind(value=self.on_slider_value)
        layout.add_widget(self.progress_slider)
        
        # 添加拆分点按钮
        self.add_split_btn = Button(
            text='在当前位置添加拆分点',
            size_hint_y=None,
            height=dp(50),
            background_color=(0.9, 0.5, 0.2, 1),
            disabled=True,
            font_name=self.get_font_name_safe()
        )
        self.add_split_btn.bind(on_press=self.add_split_point)
        layout.add_widget(self.add_split_btn)
        
        return layout
    
    def create_split_section(self):
        """创建拆分点管理区域"""
        layout = BoxLayout(orientation='vertical', size_hint_y=None, height=dp(200), spacing=dp(5))
        
        # 标题
        title = Label(
            text='拆分点列表',
            size_hint_y=None,
            height=dp(30),
            color=(0.2, 0.2, 0.2, 1),
            font_name=self.get_font_name_safe()
        )
        layout.add_widget(title)
        
        # 拆分点列表
        scroll = ScrollView()
        self.split_list = GridLayout(cols=1, size_hint_y=None, spacing=dp(2))
        self.split_list.bind(minimum_height=self.split_list.setter('height'))
        scroll.add_widget(self.split_list)
        layout.add_widget(scroll)
        
        # 清空按钮
        clear_btn = Button(
            text='清空所有拆分点',
            size_hint_y=None,
            height=dp(40),
            background_color=(0.8, 0.3, 0.3, 1),
            font_name=self.get_font_name_safe()
        )
        clear_btn.bind(on_press=self.clear_split_points)
        layout.add_widget(clear_btn)
        
        return layout
    
    def create_output_section(self):
        """创建输出设置区域"""
        layout = BoxLayout(orientation='vertical', size_hint_y=None, height=dp(100), spacing=dp(5))
        
        # 分辨率选择
        resolution_layout = BoxLayout(orientation='horizontal', size_hint_y=None, height=dp(40))
        
        resolution_label = Label(
            text='输出分辨率:',
            size_hint_x=0.3,
            color=(0.2, 0.2, 0.2, 1),
            font_name=self.get_font_name_safe()
        )
        resolution_layout.add_widget(resolution_label)
        
        self.resolution_spinner = Spinner(
            text='保持原始',
            values=['保持原始', '1080p', '720p', '480p', '360p'],
            size_hint_x=0.7
        )
        # 设置Spinner字体
        if hasattr(self.resolution_spinner, '_dropdown'):
            self.resolution_spinner._dropdown.container.font_name = self.get_font_name_safe()
        resolution_layout.add_widget(self.resolution_spinner)
        
        layout.add_widget(resolution_layout)
        
        # 输出目录选择
        output_layout = BoxLayout(orientation='horizontal', size_hint_y=None, height=dp(50))
        
        self.output_btn = Button(
            text='选择输出目录',
            size_hint_x=0.4,
            background_color=(0.5, 0.5, 0.8, 1),
            font_name=self.get_font_name_safe()
        )
        self.output_btn.bind(on_press=self.select_output_dir)
        output_layout.add_widget(self.output_btn)
        
        # 设置默认输出目录
        default_dir = self.android_permissions.get_default_output_dir()
        default_text = 'Android存储' if default_dir else '默认：视频同目录'
        
        self.output_label = Label(
            text=default_text,
            size_hint_x=0.6,
            font_name=self.get_font_name_safe(),
            color=(0.4, 0.4, 0.4, 1)
        )
        output_layout.add_widget(self.output_label)
        
        layout.add_widget(output_layout)
        
        return layout
    
    def create_process_section(self):
        """创建处理区域"""
        layout = BoxLayout(orientation='vertical', size_hint_y=None, height=dp(120), spacing=dp(5))
        
        # 开始拆分按钮
        self.split_btn = Button(
            text='开始拆分视频',
            size_hint_y=None,
            height=dp(50),
            background_color=(0.2, 0.8, 0.2, 1),
            disabled=True,
            font_name=self.get_font_name_safe()
        )
        self.split_btn.bind(on_press=self.start_split)
        layout.add_widget(self.split_btn)
        
        # 进度条
        self.process_progress = ProgressBar(
            max=100,
            value=0,
            size_hint_y=None,
            height=dp(20)
        )
        layout.add_widget(self.process_progress)
        
        # 状态标签
        self.status_label = Label(
            text='准备就绪',
            size_hint_y=None,
            height=dp(30),
            font_name=self.get_font_name_safe(),
            color=(0.3, 0.3, 0.3, 1)
        )
        layout.add_widget(self.status_label)
        
        return layout
    
    def select_video_file(self, instance):
        """选择视频文件"""
        # 在Android上优先显示设备视频列表
        if kivy_platform == 'android':
            self.show_android_video_list()
            return
        
        if PLYER_AVAILABLE:
            try:
                filechooser.open_file(
                    on_selection=self.on_file_selected,
                    filters=[
                        ('Video files', '*.mp4;*.avi;*.mov;*.mkv;*.wmv;*.3gp')
                    ]
                )
                return
            except Exception as e:
                print(f"Plyer file chooser error: {e}")
        
        # 备用文件选择器
        self.show_file_chooser()
    
    def show_file_chooser(self):
        """显示文件选择器弹窗"""
        content = BoxLayout(orientation='vertical')
        
        filechooser = FileChooserListView(
            filters=['*.mp4', '*.avi', '*.mov', '*.mkv', '*.wmv', '*.3gp']
        )
        content.add_widget(filechooser)
        
        buttons = BoxLayout(size_hint_y=None, height=dp(50), spacing=dp(10))
        
        select_btn = Button(text='选择', font_name=self.get_font_name_safe())
        cancel_btn = Button(text='取消', font_name=self.get_font_name_safe())
        
        buttons.add_widget(select_btn)
        buttons.add_widget(cancel_btn)
        content.add_widget(buttons)
        
        popup = Popup(
            title='选择视频文件',
            content=content,
            size_hint=(0.9, 0.9)
        )
        # 设置popup标题字体
        if hasattr(popup, 'title_label'):
            popup.title_label.font_name = self.get_font_name_safe()
        
        def on_select(instance):
            if filechooser.selection:
                self.on_file_selected([filechooser.selection[0]])
            popup.dismiss()
        
        def on_cancel(instance):
            popup.dismiss()
        
        select_btn.bind(on_press=on_select)
        cancel_btn.bind(on_press=on_cancel)
        
        popup.open()
    
    def show_android_video_list(self):
        """显示Android设备视频列表"""
        content = BoxLayout(orientation='vertical')
        
        # 获取视频文件
        videos = self.get_android_video_files()
        
        if not videos:
            no_videos_label = Label(
                 text='未找到视频文件\n请确保设备上有视频文件并已授予存储权限',
                 halign='center',
                 font_name=self.get_font_name_safe()
             )
            content.add_widget(no_videos_label)
        else:
            # 创建视频列表
            scroll = ScrollView()
            video_list = GridLayout(cols=1, size_hint_y=None, spacing=dp(5))
            video_list.bind(minimum_height=video_list.setter('height'))
            
            for video in videos:
                video_item = BoxLayout(
                    orientation='vertical',
                    size_hint_y=None,
                    height=dp(80),
                    spacing=dp(2)
                )
                
                # 视频名称
                name_label = Label(
                     text=video['name'],
                     size_hint_y=None,
                     height=dp(30),
                     text_size=(dp(300), None),
                     halign='left',
                     font_name=self.get_font_name_safe(),
                     color=(0.2, 0.2, 0.2, 1)
                 )
                video_item.add_widget(name_label)
                
                # 视频信息
                size_mb = video['size'] / (1024 * 1024)
                duration_str = format_duration(video.get('duration', 0))
                info_text = f"大小: {size_mb:.1f}MB"
                if video.get('duration'):
                    info_text += f" | 时长: {duration_str}"
                
                info_label = Label(
                     text=info_text,
                     size_hint_y=None,
                     height=dp(25),
                     font_size='12sp',
                     font_name=self.get_font_name_safe(),
                     color=(0.5, 0.5, 0.5, 1)
                 )
                video_item.add_widget(info_label)
                
                # 选择按钮
                select_btn = Button(
                    text='选择',
                    size_hint_y=None,
                    height=dp(25),
                    background_color=(0.3, 0.6, 0.9, 1),
                    font_name=self.get_font_name_safe()
                )
                select_btn.bind(
                    on_press=lambda x, path=video['path']: self.on_android_video_selected(path)
                )
                video_item.add_widget(select_btn)
                
                video_list.add_widget(video_item)
            
            scroll.add_widget(video_list)
            content.add_widget(scroll)
        
        # 按钮区域
        buttons = BoxLayout(size_hint_y=None, height=dp(50), spacing=dp(10))
        
        browse_btn = Button(text='浏览文件', font_name=self.get_font_name_safe())
        cancel_btn = Button(text='取消', font_name=self.get_font_name_safe())
        
        buttons.add_widget(browse_btn)
        buttons.add_widget(cancel_btn)
        content.add_widget(buttons)
        
        popup = Popup(
            title='选择视频文件',
            content=content,
            size_hint=(0.9, 0.8)
        )
        # 设置popup标题字体
        if hasattr(popup, 'title_label'):
            popup.title_label.font_name = self.get_font_name_safe()
        
        def on_browse(instance):
            popup.dismiss()
            self.show_file_chooser()
        
        def on_cancel(instance):
            popup.dismiss()
        
        browse_btn.bind(on_press=on_browse)
        cancel_btn.bind(on_press=on_cancel)
        
        popup.open()
    
    def on_android_video_selected(self, video_path):
        """Android视频选择回调"""
        self.on_file_selected([video_path])
        # 关闭弹窗
        for child in Window.children[:]:
            if hasattr(child, 'title') and child.title == '选择视频文件':
                child.dismiss()
    
    def on_file_selected(self, selection):
        """文件选择回调"""
        if selection:
            self.selected_video_path = selection[0]
            filename = os.path.basename(self.selected_video_path)
            self.file_label.text = f'已选择: {filename}'
            self.load_video_info()
    
    def load_video_info(self):
        """加载视频信息"""
        if not self.selected_video_path:
            return
        
        # 检查文件格式
        if not self.video_splitter.is_supported_format(self.selected_video_path):
            self.show_error("不支持的视频格式")
            return
        
        # 检查FFmpeg
        if not self.video_splitter.ffmpeg_available:
            self.show_error("FFmpeg未安装或不可用，请先安装FFmpeg")
            return
        
        try:
            self.video_info = VideoInfo(self.selected_video_path)
            if self.video_info.load_info():
                self.progress_slider.max = self.video_info.duration
                self.progress_slider.disabled = False
                self.play_btn.disabled = False
                self.add_split_btn.disabled = False
                self.update_position_label()
                self.update_video_info_display()
                self.check_split_ready()
            else:
                self.show_error("无法读取视频信息")
        except Exception as e:
            self.show_error(f"加载视频失败: {str(e)}")
    
    def toggle_play(self, instance):
        """切换播放状态"""
        if not FFPYPLAYER_AVAILABLE:
            self.show_error("FFPyPlayer未安装，无法播放视频")
            return
        
        if not self.is_playing:
            try:
                if self.media_player:
                    self.media_player.close_player()
                
                self.media_player = MediaPlayer(self.selected_video_path)
                self.is_playing = True
                self.play_btn.text = '暂停'
                Clock.schedule_interval(self.update_player_position, 0.1)
            except Exception as e:
                self.show_error(f"播放失败: {str(e)}")
        else:
            self.pause_video()
    
    def pause_video(self):
        """暂停视频"""
        if self.media_player:
            self.media_player.close_player()
            self.media_player = None
        
        self.is_playing = False
        self.play_btn.text = '播放'
        Clock.unschedule(self.update_player_position)
    
    def update_player_position(self, dt):
        """更新播放位置"""
        if self.media_player and self.is_playing:
            frame, val = self.media_player.get_frame()
            if val != 'eof':
                self.current_position = self.media_player.get_pts()
                if self.current_position:
                    self.progress_slider.value = self.current_position
                    self.update_position_label()
            else:
                self.pause_video()
    
    def on_slider_value(self, instance, value):
        """滑块值变化"""
        if not self.is_playing:  # 只在非播放状态下允许手动调节
            self.current_position = value
            self.update_position_label()
    
    def update_position_label(self):
        """更新位置标签"""
        if self.video_info:
            current_str = format_duration(self.current_position)
            duration_str = format_duration(self.video_info.duration)
            self.position_label.text = f'{current_str} / {duration_str}'
        else:
            self.position_label.text = '00:00:00 / 00:00:00'
    
    def seconds_to_time_str(self, seconds):
        """将秒数转换为时间字符串"""
        hours = int(seconds // 3600)
        minutes = int((seconds % 3600) // 60)
        secs = int(seconds % 60)
        return f"{hours:02d}:{minutes:02d}:{secs:02d}"
    
    def add_split_point(self, instance):
        """添加拆分点"""
        if not self.video_info:
            self.show_error("请先选择视频文件")
            return
            
        if self.current_position > 0 and self.current_position < self.video_info.duration:
            # 检查是否已存在相同的拆分点
            for point_time in self.split_points:
                if abs(point_time - self.current_position) < 1:
                    self.show_error("该位置附近已存在拆分点")
                    return
            
            self.split_points.append(self.current_position)
            self.split_points.sort()
            self.update_split_list()
            self.check_split_ready()
            self.update_size_estimate()
        else:
            self.show_error("请选择有效的拆分位置（0秒到视频结束之间）")
    
    def update_split_list(self):
        """更新拆分点列表"""
        self.split_list.clear_widgets()
        
        for i, point_time in enumerate(self.split_points):
            item_layout = BoxLayout(
                orientation='horizontal',
                size_hint_y=None,
                height=dp(40),
                spacing=dp(5)
            )
            
            time_str = format_duration(point_time)
            label = Label(
                text=f'{i+1}. {time_str}',
                size_hint_x=0.7,
                color=(0.2, 0.2, 0.2, 1)
            )
            item_layout.add_widget(label)
            
            delete_btn = Button(
                text='删除',
                size_hint_x=0.3,
                size_hint_y=None,
                height=dp(35),
                background_color=(0.8, 0.3, 0.3, 1)
            )
            delete_btn.bind(on_press=lambda x, idx=i: self.remove_split_point(idx))
            item_layout.add_widget(delete_btn)
            
            self.split_list.add_widget(item_layout)
    
    def remove_split_point(self, index):
        """删除拆分点"""
        if 0 <= index < len(self.split_points):
            self.split_points.pop(index)
            self.update_split_list()
            self.check_split_ready()
            self.update_size_estimate()
    
    def clear_split_points(self, instance):
        """清空所有拆分点"""
        self.split_points.clear()
        self.update_split_list()
        self.check_split_ready()
        self.update_size_estimate()
    
    def check_split_ready(self):
        """检查是否可以开始拆分"""
        ready = (self.selected_video_path and 
                len(self.split_points) > 0 and 
                self.video_info and 
                self.video_info.duration > 0)
        self.split_btn.disabled = not ready
    
    def select_output_dir(self, instance):
        """选择输出目录"""
        if PLYER_AVAILABLE:
            try:
                filechooser.choose_dir(
                    on_selection=self.on_output_dir_selected
                )
                return
            except Exception as e:
                print(f"Plyer dir chooser error: {e}")
        
        self.show_error("请手动设置输出目录")
    
    def on_output_dir_selected(self, selection):
        """输出目录选择回调"""
        if selection:
            self.output_dir = selection[0]
            self.output_label.text = f'输出到: {os.path.basename(self.output_dir)}'
            self.update_size_estimate()
    
    def start_split(self, instance):
        """开始拆分视频"""
        if not self.selected_video_path or not self.split_points or not self.video_info:
            self.show_error("请选择视频文件并添加拆分点")
            return
        
        # 验证拆分点
        valid, message = validate_split_points(self.split_points, self.video_info.duration)
        if not valid:
            self.show_error(message)
            return
        
        self.split_btn.disabled = True
        self.status_label.text = "正在拆分视频..."
        self.process_progress.value = 0
        
        # 在后台线程中执行拆分
        threading.Thread(target=self.split_video_thread, daemon=True).start()
    
    def split_video_thread(self):
        """拆分视频线程"""
        try:
            # 准备输出目录
            if self.output_dir:
                base_output_dir = self.output_dir
            else:
                # 尝试使用Android默认目录
                android_dir = self.android_permissions.create_app_directory()
                if android_dir:
                    base_output_dir = android_dir
                else:
                    base_output_dir = os.path.dirname(self.selected_video_path)
            
            # 创建输出子目录
            video_name = os.path.splitext(os.path.basename(self.selected_video_path))[0]
            output_dir = os.path.join(base_output_dir, f"{video_name}_segments")
            
            # 获取分辨率设置
            resolution_text = self.resolution_spinner.text
            resolution = None if resolution_text == '保持原始' else resolution_text
            
            # 显示开始通知
            self.android_notifications.show_progress_notification(
                "视频拆分", "开始拆分视频...", 0
            )
            
            # 进度回调函数
            def progress_callback(current, total, status):
                progress = (current / total * 100) if total > 0 else 0
                Clock.schedule_once(
                    lambda dt: self.update_split_progress(progress, status),
                    0
                )
                # 更新通知
                self.android_notifications.show_progress_notification(
                    "视频拆分", status, int(progress)
                )
            
            # 执行拆分
            successful_segments = self.video_splitter.split_video(
                self.selected_video_path,
                self.split_points,
                output_dir,
                resolution=resolution,
                quality='medium',
                progress_callback=progress_callback
            )
            
            # 显示完成通知
            self.android_notifications.show_completion_notification(
                "视频拆分完成",
                f"成功生成 {len(successful_segments)} 个视频片段"
            )
            
            # 拆分完成
            Clock.schedule_once(
                lambda dt: self.on_split_complete(output_dir, len(successful_segments)),
                0
            )
            
        except Exception as e:
            # 显示错误通知
            self.android_notifications.show_completion_notification(
                "视频拆分失败",
                str(e)
            )
            
            Clock.schedule_once(
                lambda dt: self.on_split_error(str(e)),
                0
            )
    
    def update_split_progress(self, progress, status):
        """更新拆分进度"""
        self.process_progress.value = progress
        self.status_label.text = status
    
    def update_size_estimate(self):
        """更新文件大小估算"""
        if not self.video_info or not self.split_points:
            return
        
        try:
            resolution = None if self.resolution_spinner.text == '保持原始' else self.resolution_spinner.text
            estimate = self.video_splitter.estimate_output_size(
                self.selected_video_path, 
                self.split_points, 
                resolution
            )
            
            if estimate:
                size_text = format_file_size(estimate['estimated_size_bytes'])
                # 可以在界面上显示估算大小
        except Exception as e:
            print(f"Size estimation error: {e}")
    
    def on_split_complete(self, output_path, segment_count):
        """拆分完成"""
        self.status_label.text = f"拆分完成！生成了 {segment_count} 个片段"
        self.process_progress.value = 100
        self.split_btn.disabled = False
        self.show_success(f"视频拆分完成！\n生成了 {segment_count} 个片段\n输出目录: {output_path}")
    
    def on_split_error(self, error_msg):
        """拆分错误"""
        self.status_label.text = "拆分失败"
        self.process_progress.value = 0
        self.split_btn.disabled = False
        self.show_error(f"拆分失败: {error_msg}")
    
    def show_error(self, message):
        """显示错误消息"""
        content_label = Label(
            text=message, 
            text_size=(dp(300), None), 
            halign='center',
            font_name=self.get_font_name_safe()
        )
        popup = Popup(
            title='错误',
            content=content_label,
            size_hint=(0.8, 0.4)
        )
        popup.open()
    
    def show_success(self, message):
        """显示成功消息"""
        content_label = Label(
            text=message, 
            text_size=(dp(300), None), 
            halign='center',
            font_name=self.get_font_name_safe()
        )
        popup = Popup(
            title='成功',
            content=content_label,
            size_hint=(0.8, 0.4)
        )
        popup.open()


if __name__ == '__main__':
    VideoSplitterApp().run()